from flask import g
from flask import request
from flask_restful import Resource

from cache.article import ArticleDetailCache
from cache.user import UserHistoryCache, UserArticleAttiudeCache
from toutiao.utils.decorators import loginrequired


class UserHistory(Resource):
    method_decorators = [loginrequired]

    def get(self):
        # 0.获取分页参数
        page = request.args.get('page', 1)
        per_page = request.args.get('per_page', 10)
        try:
            page = int(page)
            per_page = int(per_page)
        except Exception:
            page = 1
            per_page = 10
        # 1.获取文章的id列表
        article_ids = UserHistoryCache(g.user_id).get_all()
        total_count = UserHistoryCache(g.user_id).get_total_count()
        # 2.获取分页数据
        page_article_ids = article_ids[(page - 1) * per_page:page * per_page]
        # 3.遍历来获取文章的详情
        results = []
        for article_id in page_article_ids:
            article = ArticleDetailCache(article_id).get()
            # 课下作业 实现 是否点赞
            article['is_liking'] = UserArticleAttiudeCache(g.user_id).get_article_attitude(article_id)
            # article['is_liking'] = True
            results.append(article)

        # UserHistoryCache(g.user_id).clear()
        # 4.返回数据
        return {'total_count': total_count, 'page': page, 'per_page': per_page, 'results': results}
